import { saveScreenshot } from '@/services/SourceSerivce';
import { updateLoginStatus } from '@/services/UserService';
import { liveControlRecordType } from '@/types';
import {
  BorderOutlined,
  CloseOutlined,
  IdcardOutlined,
  MinusOutlined,
  UserOutlined,
} from '@ant-design/icons';
import {
  Access,
  history,
  useAccess,
  useAppData,
  useLocation,
  useModel,
  useOutlet,
} from '@umijs/max';
import { useAsyncEffect, useKeyPress } from 'ahooks';
import { Button, Dropdown, MenuProps, Modal, message } from 'antd';
import { NoticeType } from 'antd/es/message/interface';
import { useEffect, useMemo, useState } from 'react';
import { isBlank, isNotBlank } from 'web-plugin-utils';
import styles from './index.less';

const Layout = () => {
  const [_message, contextHolder] = message.useMessage();
  const { patient, setPatient } = useModel('patient');
  const access = useAccess();
  const outlet = useOutlet();
  const { routes } = useAppData();
  const { videoMatrixServer, peerServer } = useModel('global');
  const { initialState } = useModel('@@initialState');
  const allowRoutes = Object.values(routes).filter((r: any) =>
    isNotBlank(r.name),
  );
  const { liveControlRecordList, setLiveControlRecordList } =
    useModel('record');
  const _location = useLocation();
  const [userInfo, setUserInfo] = useState(
    JSON.parse(localStorage.getItem('userInfo')!)!,
  );
  const [forceOutFlag, setForceOutFlag] = useState<boolean>(false);
  const [isLiving, setIsLiving] = useState<boolean>(false);
  const currentRoute: any = useMemo(() => {
    return allowRoutes.filter((r) => r.path === _location.pathname)[0];
  }, [_location]);

  const activePatient = async (showClose: boolean = true) => {
    if (isLiving) {
      message.error('请结束直播录制/视频会议相关活动');
      return;
    }
    await window.tm?.ipcRenderer.invoke(
      'showObsModal',
      {
        path: '@/components/PatientList/index',
        data: { clickText: '患者信息' },
        showClose,
      },
      'large',
    );
  };

  useAsyncEffect(async () => {
    console.log('currentRoute', currentRoute);
    if (currentRoute) {
      document.title = `${(currentRoute as any)?.name}-可视化综合培训系统`;
      window.tm?.ipcRenderer.send('changeLocation', {
        name: currentRoute?.name,
      });
    }
    if (access.allowVideoMatrix) {
      console.log('useEffect  currentRoute', currentRoute);
      // && currentRoute.path === '/patient'
      if (patient === undefined && !currentRoute) {
        activePatient(false);
      }
    }
  }, [currentRoute]);

  useEffect(() => {
    window.osn.on('forceOut', (event: any, result: any) => {
      setForceOutFlag(true);
    });

    window.osn.on('setLiving', (e, data: boolean) => {
      console.log('setLiving', data);
      setIsLiving(data);
    });
    window.osn.on(
      'showMessage',
      (
        e,
        data: {
          type: NoticeType;
          message: string;
        },
      ) => {
        console.log('showMessage', data);
        message.open({
          type: data.type,
          content: data.message,
        });
      },
    );

    window.osn.on('updatePatientActive', (e, data: any) => {
      console.log('updatePatientActive', data);
      setPatient(data);
    });
    window.osn.on('stopControlRecord', (e, data: liveControlRecordType) => {
      console.log('stopControlRecord', data);
      const index = liveControlRecordList.findIndex(
        (x) => x.m7sRecordId === data.m7sRecordId,
      );
      if (index > -1) {
        liveControlRecordList.splice(index, 1);
        setLiveControlRecordList(liveControlRecordList);
      }
    });

    window.tm?.ipcRenderer.invoke('createObsModal', {});
  }, []);

  useKeyPress('ctrl.alt.a', async () => {
    if (
      !currentRoute?.hideInMenu &&
      isNotBlank(initialState?.screenshotWorkName)
    ) {
      const result = await saveScreenshot(
        videoMatrixServer,
        initialState!.screenshotWorkName!,
      );
      if (result.success) {
        _message.success('截图成功');
      } else {
        _message.error('截图失败');
      }
    }
  });
  const [fileList, setFileList] = useState([
    {
      uid: '-1',
      name: '',
      status: '',
      file: userInfo?.avatar,
      url: userInfo?.avatar,
      thumbUrl: userInfo?.avatar,
    },
  ]);
  const items: MenuProps['items'] = [
    {
      key: '0',
      label: (
        <a
          onClick={async () => {
            await window.tm?.ipcRenderer.invoke(
              'showObsModal',
              {
                path: '@/components/User/setting.tsx',
                data: { type: 'avatar' },
                title: '修改头像',
              },
              {
                width: 500,
                height: 280,
              },
            );
          }}
        >
          修改头像
        </a>
      ),
    },
    {
      key: '1',
      label: (
        <a
          onClick={async () => {
            await window.tm?.ipcRenderer.invoke(
              'showObsModal',
              {
                path: '@/components/User/setting.tsx',
                data: { type: 'name' },
                title: '修改昵称',
              },
              {
                width: 500,
                height: 280,
              },
            );
          }}
        >
          修改昵称
        </a>
      ),
    },
    {
      key: '2',
      label: (
        <a
          onClick={async () => {
            await window.tm?.ipcRenderer.invoke(
              'showObsModal',
              {
                path: '@/components/User/setting.tsx',
                data: { type: 'password' },
                title: '修改密码',
              },
              {
                width: 500,
                height: 280,
              },
            );
          }}
        >
          修改密码
        </a>
      ),
    },
    {
      key: '3',
      label: (
        <a
          onClick={() => {
            localStorage.removeItem('userInfo');
            localStorage.removeItem('tokenIssueTime');
            localStorage.removeItem('token');
            window.tm?.ipcRenderer.send('openLogin');
            updateLoginStatus(peerServer, 0, userInfo?.id);
            window.tm?.ipcRenderer.send('toClose');
          }}
        >
          退出登陆
        </a>
      ),
    },
  ];

  return currentRoute?.hideInMenu ? (
    outlet
  ) : (
    <div className={styles.mainLayout}>
      {contextHolder}
      <div className={styles.topHeader}>
        <div className={styles.softTitle}>
          <div className={styles.imgIcon}>
            <img src="/img/图标@2x.png" />
          </div>
          <div className={styles.title}>可视化综合培训系统</div>
          <div className={styles.userInfo}>
            {isNotBlank(userInfo?.userName as string) && (
              <Dropdown menu={{ items }} placement="bottom" arrow>
                <Button icon={<UserOutlined />}>{userInfo?.userName}</Button>
              </Dropdown>
            )}
          </div>
          <div className={styles.win_control}>
            <Button
              type="text"
              icon={<MinusOutlined />}
              onClick={() => {
                window.tm?.ipcRenderer.send('toMin');
              }}
            />
            <Button
              type="text"
              icon={<BorderOutlined />}
              onClick={() => {
                window.tm?.ipcRenderer.send('toMax');
              }}
            />
            <Button
              danger
              type="text"
              icon={<CloseOutlined />}
              onClick={() => {
                localStorage.removeItem('userInfo');
                localStorage.removeItem('tokenIssueTime');
                localStorage.removeItem('token');
                if (isBlank(userInfo?.userName as string)) {
                  window.tm?.ipcRenderer.send('openLogin');
                }
                window.tm?.ipcRenderer.send('toClose');
                updateLoginStatus(peerServer, 0, userInfo.id);
              }}
            />
          </div>
        </div>
        <div className={styles.menus}>
          <div className={styles.menuIcons}>
            {allowRoutes
              .filter((r: any) => !r.hideInMenu)
              .map((r: any) => (
                <Access
                  key={r.username}
                  accessible={
                    isNotBlank(userInfo?.userName as string)
                      ? (access as any)[r.access as any] ?? true
                      : true
                  }
                >
                  {/* r.path === '/settings' */}
                  <div
                    onClick={async () => {
                      if (r.path === currentRoute.path) return;
                      if (isLiving) {
                        message.error('请结束直播录制/视频会议相关活动');
                        return;
                      }
                      if (r.path !== '/obs') {
                        await window.tm?.ipcRenderer.invoke('shutdownOBS', r);
                      }
                      history.replace(r.path);
                    }}
                    className={[
                      styles.menuIcon,
                      r.path === _location.pathname ? styles.active : '',
                    ].join(' ')}
                  >
                    <div className={styles.menuIconImg}>
                      <img src={r.imgIcon} />
                    </div>
                    <div className={styles.menuIconTitle}>{r.name}</div>
                  </div>
                </Access>
              ))}
          </div>
          <Access
            accessible={
              isNotBlank(userInfo?.userName as string) &&
              access.allowVideoMatrix
            }
          >
            <div className={styles.patient}>
              <div className={styles.patientContent}>
                <div className={styles.patientUser}>
                  <UserOutlined />
                  <div>{patient?.name}</div>
                </div>
                <div className={styles.patientHo}>
                  <IdcardOutlined />
                  <div>{patient?.hospitalNumber}</div>
                </div>
                <div className={styles.patientList}>
                  {/*<PatientList clickText="患者列表" />*/}
                  <div
                    onClick={async () => {
                      await activePatient();
                    }}
                  >
                    患者信息
                  </div>
                </div>
              </div>
            </div>
          </Access>
        </div>

        {/*{isLiving && (*/}
        {/*  <div*/}
        {/*    className={styles.isLiving}*/}
        {/*    onClick={() => {*/}
        {/*      message.error('请结束直播录制/视频会议相关活动');*/}
        {/*    }}*/}
        {/*  >*/}
        {/*    锁定页面中*/}
        {/*  </div>*/}
        {/*)}*/}
      </div>
      <div className={styles.content}>{outlet}</div>
      <Modal
        title={<div className={styles.customModalTitle}>异常登录提醒</div>}
        open={forceOutFlag}
        keyboard={false}
        closable={false}
        centered={true}
        width={350}
        footer={
          <div className={`ant-modal-footer ${styles.centeredFooter}`}>
            <Button
              className={styles.buttonStyle}
              onClick={() => {
                window.tm?.ipcRenderer.send('openLogin');
                window.tm?.ipcRenderer.send('toClose');
              }}
            >
              确定
            </Button>
          </div>
        }
      >
        <div className={styles.centeredFooter}>
          <span>尊敬的用户：{userInfo?.userName}</span>
          <span>您的账户在别处登录，点击确定退出</span>
        </div>
      </Modal>
    </div>
  );
};

export default Layout;
